package com.fast.admin.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fast.admin.entity.sys.Role;
import com.fast.admin.entity.sys.User;
import com.fast.admin.entity.sys.UserRole;
import com.fast.admin.service.sys.IRoleService;
import com.fast.admin.service.sys.IUserRoleService;
import com.fast.admin.service.sys.IUserService;
import com.fast.common.base.BaseController;
import com.fast.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Title：UserController
 * @author：ylc
 * @date：2018/8/1 11:41
 * @version：1.0
 **/
@Controller
@RequestMapping(value = "/sys/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserRoleService userRoleService;
    @Override
    protected String getPrefix() {
        return "sys/user/";
    }

    @Override
    protected String formView(Model model, Long id) {
        model.addAttribute("role", roleService.selectList(null));
        return super.formView(model, id);
    }

    @ResponseBody
    @GetMapping(value = "/page")
    public R page(@RequestParam Map<String, Object> params, User user){
        return R.ok(userService.findPage(params, new QueryWrapper<>(user)));
    }

    @ResponseBody
    @GetMapping(value = "/get/{id}")
    public R get(@PathVariable("id") Long id){
        List<UserRole> userRoles = userRoleService.selectByUserId(id);
        Long[] array = userRoles.stream().map(UserRole::getRoleId).toArray(Long[]::new);
        return R.ok(userService.selectById(id)).put("roleId", array);
    }

    @ResponseBody
    @PostMapping(value = "/save")
    public R save(User user, String roleId){
        userService.addOrUpdate(user, roleId);
        return R.ok();
    }
}
